package com.ycx.furns.service.impl;

import com.ycx.furns.dao.FurnDAO;
import com.ycx.furns.dao.OrderDAO;
import com.ycx.furns.dao.OrderItemDAO;
import com.ycx.furns.dao.impl.FurnDAOImpl;
import com.ycx.furns.dao.impl.OrderDAOImpl;
import com.ycx.furns.dao.impl.OrderItemDAOImpl;
import com.ycx.furns.entity.Cart;
import com.ycx.furns.entity.Furn;
import com.ycx.furns.entity.Order;
import com.ycx.furns.entity.OrderItem;
import com.ycx.furns.service.OrderService;

import java.util.Collection;
import java.util.Date;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    OrderDAO orderDAO = new OrderDAOImpl();
    OrderItemDAO orderItemDAO = new OrderItemDAOImpl();
    FurnDAO furnDAO = new FurnDAOImpl();

    @Override
    public String saveOrder(Cart cart, int memberId) {
        String orderId = System.currentTimeMillis() + "" + memberId;
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, memberId);
        orderDAO.saveOrder(order);

        Collection<Cart.Item> items = cart.getItems();
        for (Cart.Item item : items) {
            OrderItem orderItem = new OrderItem(null, item.getName(), item.getPrice(),
                    item.getNum(), item.getTotalPrice(), orderId);
            orderItemDAO.saveOrderItem(orderItem);

            Furn furn = furnDAO.getFurnById(item.getId());
            furn.setSales(furn.getSales() + item.getNum());
            furn.setStock(furn.getStock() - item.getNum());
            furnDAO.updateFurn(furn);
        }


        return orderId;
    }

    @Override
    public List<Order> queryOrders(int memberId) {
        return orderDAO.queryOrders(memberId);
    }

    @Override
    public List<OrderItem> queryOrderItems(String orderId) {
        return orderItemDAO.queryOrderItemsById(orderId);
    }


}
